/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package MidiGui;

import java.awt.BorderLayout;
import java.util.Collections;
import java.util.Vector;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import midi.Keyboard;
import midi.MidiPlayer;
import midi.NotePlayListener;
import music.*;
import music.types.MidiNote;
import music.types.NoteTypes;
import structures.NotesManager;

/**
 *
 * @author TJ
 */
public class KeyboardPanel extends JPanel implements NotePlayListener,ListSelectionListener{
    Keyboard k;
    private StaffPanel p;
    private JList j;
    public KeyboardPanel(){
        init();
    }
    
    private void init() {
        k=new Keyboard();
        k.addNotePlayedListener(this);
        p=new StaffPanel();
        Vector<Instrument> inst=new Vector<Instrument>();
        for(javax.sound.midi.Instrument i : MidiPlayer.getMidiPlayer().getInstrumentList()) {
            inst.add(new Instrument(i.getName(),i.getPatch().getProgram()));
        }
        Collections.sort(inst);
        j=new JList(inst);
        j.setFocusable(false);
        DefaultListSelectionModel d=new DefaultListSelectionModel();
        d.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        j.setSelectionModel(d);
        j.addListSelectionListener(this);
        JScrollPane sp=new JScrollPane(j);
        this.setLayout(new BorderLayout());
        this.add(p,BorderLayout.CENTER);
        this.add(sp,BorderLayout.EAST);
    }

    @Override
    public void noteStarted(MidiNote n) {
        populateNotes();
    }

    @Override
    public void noteStopped(MidiNote n) {
         populateNotes();
    }
    public void populateNotes() {
        NotesManager n=p.getStaff(0).getMeasure(0).getNotes();
        n.clearAllNotes();
        Note n2=new Note(NoteTypes.QUARTER, k.getNotesPlaying());
        n.getVoice(1).addNoteAt(0, n2);
        repaint();
    }

    @Override
    public void valueChanged(ListSelectionEvent e) {
        k.changeInstrument(((Instrument)j.getSelectedValue()).getProgram());
    }
}
